<template>
	<div class="newLeave">
		<div class="teach_h  classIndex_h clear">
			<em @click="goback()">请假申请</em>
			<strong><i>></i> 新建申请</strong>
		</div>
		<!--  -->
		<div class="newLeave_from">
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
				<el-form-item label="请假人" prop="dummy_id">
					<el-select filterable v-model="ruleForm.dummy_id" @change="getApprove()" placeholder="请选择">
						<el-option v-for="(item, index) in dummyList" :label="item.name" :value="item.id" :key="index"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="请假类型" prop="leave_style">
					<el-select filterable v-model="ruleForm.leave_style" placeholder="请选择">
						<el-option label="事假" :value="0"></el-option>
						<el-option label="病假" :value="1"></el-option>
						<el-option label="婚假" :value="2"></el-option>
						<el-option label="丧假" :value="3"></el-option>
						<el-option label="其他" :value="4"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="开始时间" required>
					<el-form-item prop="start_time">
						<el-date-picker type="datetime" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss" v-model="ruleForm.start_time"></el-date-picker>
					</el-form-item>
				</el-form-item>
				<el-form-item label="结束时间" required>
					<el-form-item prop="end_time">
						<el-date-picker type="datetime" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss" v-model="ruleForm.end_time"></el-date-picker>
					</el-form-item>
				</el-form-item>
				<el-form-item label="审批人" prop="approve_id">
					<el-select filterable v-model="ruleForm.approve_id" placeholder="请选择审批人">
						<el-option v-for="item in approveList" :label="item.name" :value="item.id" :key="item.id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="请假理由" prop="content">
					<el-input type="textarea" :rows="6" resize="none" maxlength="200" v-model.trim="ruleForm.content"></el-input>
					<span class="numberWord"><i>{{ ruleForm.content.length }}</i>/200</span>
				</el-form-item>
				<el-form-item label="图片">
					<div class="publishFrom_ box">
						<img v-if="selectFileOrNot" :src="previewImgURL" class="avatar">
						<div class="publishFrom_b" v-else>
							<i class="ipm image_up"></i>
							<p>点击上传图片</p>
							<p>支持jpg/png/jpegi格式</p>
						</div>
						<uploader :options="uploadOptions" :autoStart="false" ref="uploader" :file-status-text="statusText" @file-added="fileAdd" @files-submitted="fileSubmit" @file-removed="fileRemoved" @file-success="fileSuccess" @file-error="fileFail" class="uploader-album">
							<uploader-unsupport></uploader-unsupport>
							<uploader-btn :directory="false" :attrs="attrs" v-if="selectFileShow" :single="true">
								<i class="ipm video_up"></i>
							</uploader-btn>
						</uploader>
					</div>
				</el-form-item>
				<el-form-item class="buttonCSS" label-width="0">
					<el-button @click="resetForm('ruleForm')" type="primary" plain>取消</el-button>
					<el-button type="primary" @click="submitForm('ruleForm')" v-preventReClick>提交申请</el-button>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>
<script>
export default {
	name: '',
	data() {
		return {
			pickerOptions: {
				disabledDate: (time) => {
					return time.getTime() < Date.now() - 8.64e7;
				}
			},
			dummy: '',
			dummyList: [],
			leaveType: [],
			approveList: [],
			ruleForm: {
				dummy_id: '',
				leave_style: '', //请假类型
				start_time: '',
				end_time: '',
				approve_id: '', //审核人
				content: '', //简要
				picture: [], //图片
			},
			rules: {
				dummy_id: [
					{ required: true, message: '请选择请假人', trigger: 'change' }
				],
				leave_style: [
					{ required: true, message: '请选择请假类型', trigger: 'change' }
				],
				start_time: [
					{ required: true, message: '请选择开始时间', trigger: 'change' }
				],
				end_time: [
					{ required: true, message: '请选择结束时间', trigger: 'change' }
				],
				approve_id: [
					{ required: true, message: '请选择审批人', trigger: 'change' }
				],
				content: [
					{ required: true, message: '请选择请假理由', trigger: 'change' }
				]
			},


			statusText: {
				success: '上传成功',
				error: '上传出错',
				uploading: '正在上传...',
				paused: '暂停',
				waiting: '等待上传'
			},
			selectFileOrNot: false, //是否选中文件
			uploadInfo: {
				file_name: '',
				file_path: '',
				file_size: 0
			},
			attrs: {
				accept: ['image/*']
			},

			uploadOptions: {
				target: this.BASE_URL + '/api/resource/res_upload_permanent',
				testChunks: false,
				headers: { Authorization: `Bearer ` + this.$g.access_token },
			},
			selectFileShow: true, //是否显示选择文件按钮
			uploadRetryTimes: 100, //文件最大重传次数
			uploaderNumber: 0,
			previewImgURL: '',
			uploadNumber: 0,
			fileNumber: 0,
			fileBol: true
		}
	},
	watch: {
		'changData'(val, newval) {
			this.path = sessionStorage.getItem('classId')
			this.getLeaveType()
			this.getRelation();
		}
	},
	computed: {
		changData() {
			return deep_clone(this.$store.state.changData);
		},
	},
	created() {
		this.getLeaveType()
		this.getRelation();
	},
	methods: {

		goback() {
			this.$router.back(-1)
		},
		/**
		 * 数据提交
		 * @DateTime 2020-03-05T17:38:02+0800
		 * @return   {[type]}                 [description]
		 */
		saveLeave() {

			let success = (res => {
				this.$message.success(res.msg);
				setTimeout(() => {
					this.$router.back(-1)
				}, 1000);
			});

			let fail = (res => {
				this.fileBol = false
				this.$message.error(res.msg);
			})
			var params = {
				dummy_id: this.ruleForm.dummy_id,
				leave_style: this.ruleForm.leave_style,
				start_time: this.ruleForm.start_time,
				end_time: this.ruleForm.end_time,
				approve_id: this.ruleForm.approve_id,
				content: this.ruleForm.content,
				picture: this.ruleForm.picture,
			};
			this.$ajax.post('api/leave/leave', params, { func: { success: success, fail: fail } })
		},
		//获取请假人
		getRelation() {
			let success = (res => {
				let data = res.data;
				this.dummyList = data;
				if (data.length > 0) {
					this.ruleForm.dummy_id = data[0].id;
				}
				this.getApprove();
			});
			this.$ajax({
				url: 'api/leave/get_leave_userid',
				method: 'get',
				params: {
					userid: this.$store.getters.userInfo.id
					// type: 3 
				},
				func: { success: success }
			})
		},
		//审批人
		getApprove() {
			let success = (res => {
				let data = res.data;
				this.approveList = data;
			});

			this.$ajax({
				url: '/api/leave/get_author_by_userid',
				method: 'get',
				params: {
					userid: this.ruleForm.dummy_id,
				},
				func: { success: success }
			})

		},
		//请假类型
		getLeaveType() {
			let success = (res => {
				let data = res.data;
				this.leaveType = parseInt(data)
			});
			this.$ajax({
				url: 'api/leave/manage_leave_list',
				method: 'get',
				params: { data_type: 1 },
				func: { success: success }
			})
		},

		//检查是不是两位数字，不足补全
		check(str) {
			str = str.toString();
			if (str.length < 2) {
				str = '0' + str;
			}
			return str;
		},
		//判断结束时间不能小于开始时间
		getTime() {

			var dateS = new Date(this.ruleForm.startDate);
			var dateE = new Date(this.ruleForm.endDate);

			var timeS = Date.parse(dateS);
			var timeE = Date.parse(dateE);
			if (timeE <= timeS) {
				this.$message.error('结束时间不能小于开始时间');
				return
			}
		},
		/**
		 * 验证表单
		 * @DateTime 2020-03-05T17:37:36+0800
		 * @param    {[type]}                 formName [description]
		 * @return   {[type]}                          [description]
		 */
		submitForm(formName) {


			if (this.ruleForm.start_time > this.ruleForm.end_time || this.ruleForm.end_time === this.ruleForm.start_time) {
				this.$message.error('结束时间不能小于或等于开始时间');
				return
			}
			this.$refs[formName].validate((valid) => {
				if (valid) {
					this.fileNumber = this.$refs.uploader.uploader.fileList.length
					if (this.fileNumber > 0 && this.fileBol) {
						this.fileUpload();
					} else {
						this.saveLeave();
					}

				} else {
					return false;
				}
			});
		},
		resetForm(formName) {
			this.$router.back(-1)
		},
		//上传成功的事件  
		fileSuccess(rootFile, file, message, chunk) {
			this.uploadNumber++
			var mess = JSON.parse(message);
			mess = handleResponseData(mess)
			if (parseInt(mess.data.status) === 1) {
				this.uploaderNumber++
				this.ruleForm.picture.push(mess.data.file_path);
				if (this.uploaderNumber === this.$refs.uploader.uploader.fileList.length) {
					this.saveLeave();
				}

			} else if (mess.status === 'fail') {
				this.$message.error(mess.msg + ' ' + file.name)
				this.$refs.uploader.uploader.cancel()
			}
		},
		fileFail(rootFile, file, message, chunk) {
			var mess = eval('(' + message + ')');
			if (parseInt(mess.error) === 401 && this.uploadRetryTimes > 0) {
				let callbcak = (data => {
					this.uploadRetryTimes--;
					this.$refs.uploader.uploader.retry(file);
				})
				this.get_access_token(callbcak);
			} else {
				this.$message.error(mess.msg);
			}
		},
		fileSubmit(files, fileList, event) {
			var arrImg = ['image/jpg', 'image/jpeg', 'image/bmp', 'image/gif', 'image/png']

			if (this.$refs.uploader.uploader.fileList.length >= 2) {
				this.$refs.uploader.uploader.fileList.splice(0, 1)
				this.$refs.uploader.uploader.files.splice(0, 1)
			}
			// replace(/\.\w+$/, '.png')

			for (var i = 0; i < fileList.length; i++) {
				var ext = fileList[i].name.split('.').pop();
				var file_type = fileList[i].fileType;


				if (!arrImg.includes(file_type)) {

					this.$message.warning("只支持jpg, jpeg, gif, png, bmp格式图片")
					this.$refs.uploader.uploader.removeFile(fileList[i]);
					return

				} else if (fileList[i].size === 0) {

					this.$refs.uploader.uploader.cancel();
					this.$message.error('上传文件大小不能小于0');
					this.selectFileShow = true;
				} else if (fileList[i].size > 10480000) {
					this.$message.warning('只允许上传10M以内的文件');
					this.$refs.uploader.uploader.removeFile(fileList[i]);
				} else {

					fileList[i].fileType = 'image/png'
					fileList[i].name = fileList[i].name.replace(/\.\w+$/, '.png')
					fileList[i].relativePath = fileList[i].relativePath.replace(/\.\w+$/, '.png')
					this.previewImgURL = window.URL.createObjectURL(fileList[i].file)

				}
			}
		},
		fileAdd(file, fileList) {

			this.previewImgURL = window.URL.createObjectURL(file.file)
			this.ruleForm.select_or_not = '1';
			this.uploadInfo.file_size = file.size;
			this.selectFileOrNot = true;
			if (this.$refs.uploader.uploader.fileList.length < 4) {
				this.selectFileShow = true;
			} else {
				this.selectFileShow = false;
			}

		},
		fileRemoved(file) {
			this.ruleForm.select_or_not = '';
			this.selectFileOrNot = false;
			if (this.$refs.uploader.uploader.fileList.length < 4) {
				this.selectFileShow = true;
			} else {
				this.selectFileShow = false;
			}

		},
		fileUpload() {
			this.$refs.uploader.uploader.resume();
		},
	}
}
</script>